package com.lyf.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

/**
 * 数据库连接的一个工具类
 */
public class DBTools {

    /**
     * 通过阿里巴巴的druid数据库连接池得到一个数据库连接
     * @return
     */
    public static DataSource getDataSource(){
        DruidDataSource ds = new DruidDataSource();
        Properties p = new Properties();
        try(InputStream is = com.lyf.utils.DBTools.class.getClassLoader().getResourceAsStream("db.properties")){
            p.load(is);
        }catch (Exception e){
            e.printStackTrace();
        }

        //加载驱动
        try{
            Class.forName(p.getProperty("driverClassName"));
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("p:" + p.getProperty("jdbcUrl"));
        ds.setUrl(p.getProperty("jdbcUrl"));
        ds.setUsername(p.getProperty("username"));
        ds.setPassword(p.getProperty("password"));
        return ds;
    }


    public static QueryRunner getQueryRunner(){
        QueryRunner qr = new QueryRunner(getDataSource());
        return qr;
    }

    public static void main(String[] args) {
        System.out.println("ds:" +getDataSource());
    }
}
